package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.ChartData;
import com.chart.chart.domian.ChartLegendData;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.domian.vo.ChartXData;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.ColorUtils;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.chart.web.controller.chart.sta.LineChartController.extractDataFromList;
import static com.chart.web.controller.chart.sta.LineChartController.setCellValue;

/**
 * 柱状图
 *
 * @author chart
 */
@RestController
@RequestMapping("/bar/chart")
public class BarChartController extends BaseController {


    @Autowired
    private IChartConfigsService chartConfigsService;


    /**
     * 将原始列表分割成大小为 groupSize 的多个子列表。
     *
     * @param originalList 原始列表
     * @param groupSize    每个子列表的大小
     * @return 包含多个子列表的列表
     */
    public static List<List<Object>> splitList(List<Object> originalList, int groupSize) {
        List<List<Object>> groupedLists = new ArrayList<>();
        int size = originalList.size();
        for (int i = 0; i < size; i += groupSize) {
            int end = Math.min(size, i + groupSize);
            List<Object> sublist = originalList.subList(i, end);
            groupedLists.add(new ArrayList<>(sublist));
        }
        return groupedLists;
    }

    //堆叠柱状图
   /* @PostMapping("/stackedColumn/importData")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {

        // 提取数据
        List<List<String>> getdata = extractDataFromListNullString(chartDateTto.getDataList());
        int sizeLine = getdata.size();
        System.out.println("我是有多少列" + sizeLine);
        // 打印原始数据
        for (List<String> getdatum : getdata) {
            System.out.println(getdatum);
        }
        // 获取第一行数据（数据名行）
        List<String> strings = getdata.get(0);
        int previousNonZeroIndex = -1;
        ArrayList<Object> arrayList = new ArrayList<>();
        for (int i = 1; i < strings.size(); i++) {
            String value = strings.get(i);
            if (!value.equals("0")) {
                if (previousNonZeroIndex != -1) {
                    int columnsBetween = i - previousNonZeroIndex;
                    arrayList.add(columnsBetween);
                }
                previousNonZeroIndex = i;
            }
        }

        // 移除第一行和第二行（如果需要）
        getdata.remove(0);
        getdata.remove(0);
        Object arr0 = arrayList.get(0);
        Integer integerValue = (Integer) arr0;
        int line = integerValue;
        System.out.println("我是中间隔的列数" + line);
        int number = sizeLine / line; //列的数据
        // 创建一个ArrayList的List来存储每一列的数据
        List<List<Double>> columnData = new ArrayList<>();
        // 初始化columnData，假设getdata不为空且至少有一行数据
        if (!getdata.isEmpty()) {
            int numColumns = getdata.get(0).size() - 1; // 减去1，因为我们要移除每行的第一列
            for (int i = 0; i < numColumns; i++) {
                columnData.add(new ArrayList<>());
            }
        }

        // 获取seriesName列表
        ArrayList<String> seriesName = new ArrayList<>();

        // 遍历excel的每一行数据
        for (int rowIndex = 0; rowIndex < getdata.size(); rowIndex++) {
            List<String> row = getdata.get(rowIndex);
            String firstColumnValue = row.remove(0); // 移除第一列并获取其值
            seriesName.add(firstColumnValue);

            for (int colIndex = 0; colIndex < row.size(); colIndex++) {
                String cellValue = row.get(colIndex);
                try {
                    double numericValue = Double.parseDouble(cellValue);
                    columnData.get(colIndex).add(numericValue);
                } catch (NumberFormatException e) {
                    System.err.println("Invalid number format: " + cellValue);
                }
            }
        }

        ArrayList<Object> arrayLists = new ArrayList<>();
        for (int colIndex = 0; colIndex < columnData.size(); colIndex++) {
            arrayLists.add(columnData.get(colIndex));
        }

        // 分割 arrayLists
        List<List<Object>> groupedLists = splitList(arrayLists, line);

        // 打印分组后的数据
        for (int i = 0; i < groupedLists.size(); i++) {
            System.out.println("Group " + (i + 1) + ": " + groupedLists.get(i));
        }

        // 以下操作json
        String chartValue = chartDateTto.getChartValue();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(chartValue);
        ArrayNode dataset = (ArrayNode) rootNode.path("dataset");

        // 查找并保留第一个含有 source 的对象，删除其他含有 source 的对象
        JsonNode firstSourceNode = null;
        int firstSourceNodeIndex = -1;
        for (int i = 0; i < dataset.size(); i++) {
            JsonNode node = dataset.get(i);
            if (node.has("source")) {
                if (firstSourceNode == null) {
                    // 记录第一个含有 source 的对象，并保存其索引
                    firstSourceNode = node;
                    firstSourceNodeIndex = i;
                } else {
                    // 删除其他含有 source 的对象
                    dataset.remove(i);
                    i--; // 调整索引，因为我们删除了一个元素
                }
            }
        }

        // 根据 groupedLists.size() 的值复制 firstSourceNode，并添加到 dataset 中
        int requiredDatasets = groupedLists.size();
        int insertIndex = firstSourceNodeIndex + 1; // 插入位置在第一个 source 对象之后
        for (int i = 1; i < requiredDatasets; i++) { // 从1开始，因为第一个已经存在
            dataset.insert(insertIndex, firstSourceNode.deepCopy());
            insertIndex++; // 每次插入后，更新插入位置
        }

        // 更新 dataset 中每个 source 对象的 source 数组值
        int groupIndex = 0;
        for (JsonNode node : dataset) {
            if (node.has("source")) {
                ArrayNode sourceArray = (ArrayNode) node.get("source");

                // 确保 sourceArray 与 groupedLists 的大小一致
                sourceArray.removeAll();
                List<Object> groupData = groupedLists.get(groupIndex);
                for (Object item : groupData) {
                    // 将每个项转换为 JsonNode
                    ArrayNode arrayNode = objectMapper.createArrayNode();
                    ((List<Double>) item).forEach(arrayNode::add);
                    sourceArray.add(arrayNode);
                }
                groupIndex++;
            }
        }

        // 打印更新后的 dataset
        System.out.println("更新后的 dataset: " + dataset.toString());

        // 打印完整的 JSON 数据
        String updatedJson = rootNode.toString();
        System.out.println("完整的 JSON 数据: " + updatedJson);


        ArrayList<Object> newList = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(updatedJson);

        newList.add(chartSmartVo);
        System.out.println(updatedJson);


        return AjaxResult.success(newList);


    }*/


    //堆叠柱状图

    @PostMapping("/stackedColumn/importData")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        Integer configId = chartDateTto.getConfigId();
        if (configId == 1) {


            //基础制图
            Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());
            List<List<String>> getData = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getData)) {
                return AjaxResult.error("请填充数据");
            }

            // Extract and filter the first row
            List<String> firstName = new ArrayList<>();
            List<String> nameList = getData.get(0);

            for (String s : nameList) {
                if (ObjectUtils.isNotEmpty(s) && !s.isEmpty()) {
                    firstName.add(s);
                }
            }

            List<String> roomName = new ArrayList<>();
            List<List<String>> list = new ArrayList<>();
            list.add(firstName);

            List<Map<String, Object>> datasets = new ArrayList<>();

            for (int i = 1; i < getData.size(); i++) {
                List<String> rowData = getData.get(i);
                if (!CollectionUtils.isEmpty(rowData)) {
                    List<String> data = new ArrayList<>();
                    for (String s : rowData) {
                        if (ObjectUtils.isNotEmpty(s) && !s.isEmpty()) {
                            data.add(s);
                        }
                    }

                    if (data.size() == 1) {
                        if (i != 1) {
                            Map<String, Object> dataset = new HashMap<>();
                            dataset.put("source", list);
                            datasets.add(dataset);
                            list = new ArrayList<>();
                            list.add(firstName);
                        }
                        roomName.add(data.get(0));
                    } else {
                        list.add(data);
                        if (i == getData.size() - 1) {
                            Map<String, Object> dataset = new HashMap<>();
                            dataset.put("source", list);
                            datasets.add(dataset);
                        }
                    }
                }
            }

            // Parse chart value JSON and modify it
            JSONObject jsonObject = JSON.parseObject(chartDateTto.getChartValue());
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject seriesTemplate = series.get(0);
            List<JSONObject> sDatas = new ArrayList<>();

            if (roomName.isEmpty()) {
                for (int i = 1; i < firstName.size(); i++) {
                    JSONObject object = new JSONObject();
                    object.putAll(seriesTemplate);
                    object.put("name", firstName.get(i));
                    sDatas.add(object);
                }
            } else {
                for (int i = 0; i < roomName.size(); i++) {
                    for (int j = 1; j < firstName.size(); j++) {
                        JSONObject object = new JSONObject();
                        object.putAll(seriesTemplate);
                        object.put("stack", roomName.get(i));
                        object.put("datasetIndex", i);
                        object.put("name", firstName.get(j));
                        sDatas.add(object);
                    }
                }
            }

            jsonObject.put("dataset", datasets);
            jsonObject.put("series", sDatas);

            // Handle the legend as a JSONArray
            Object legendObject = jsonObject.get("legend");
            if (legendObject instanceof JSONArray) {
                JSONArray legendArray = (JSONArray) legendObject;
                // Assuming you want to modify the first object in the array
                if (!legendArray.isEmpty()) {
                    JSONObject legend = legendArray.getJSONObject(0);
                    List<ChartLegendData> chartLegendData = new ArrayList<>();
                    for (int i = 1; i < firstName.size(); i++) {
                        ChartLegendData data = new ChartLegendData();
                        data.setName(firstName.get(i));
                        chartLegendData.add(data);
                    }
                    legend.put("data", chartLegendData);
                }
            } else if (legendObject instanceof JSONObject) {
                JSONObject legend = (JSONObject) legendObject;
                List<ChartLegendData> chartLegendData = new ArrayList<>();
                for (int i = 1; i < firstName.size(); i++) {
                    ChartLegendData data = new ChartLegendData();
                    data.setName(firstName.get(i));
                    chartLegendData.add(data);
                }
                legend.put("data", chartLegendData);
                jsonObject.put("legend", legend);
            }


            // series  itemStyle  的 barBorderWidth和 barBorderColor
            // 获取series数组
            List<JSONObject> seriesList = (List<JSONObject>) jsonObject.get("series");

            // 遍历series数组
            for (JSONObject seriesObj : seriesList) {
                JSONObject itemStyle = seriesObj.getJSONObject("itemStyle");
                if (itemStyle != null) {
                    // 删除 barBorderWidth 和 barBorderColor
                    itemStyle.remove("barBorderWidth");
                    itemStyle.remove("barBorderColor");
                }
            }

            ArrayList<ChartSmartVo> newList = new ArrayList<>();
            // 获取ChartConfigs对象
            ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
            // 创建新的ChartSmartVo对象并设置属性
            ChartSmartVo chartSmartVo = new ChartSmartVo();
            chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
            chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
            chartSmartVo.setConfigValue(JSON.toJSONString(jsonObject));
            chartSmartVo.setChartTypeId(configs.getChartTypeId());

            newList.add(chartSmartVo);
            System.out.println(JSON.toJSONString(jsonObject));
            return AjaxResult.success(newList);


        }
        if (configId == 8) {
            //专家图例
            String chartValue = chartDateTto.getChartValue();
            List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());
            System.out.println(chartValue);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode chartValueJson = objectMapper.readTree(chartValue);


            // 获取dataset节点并替换source节点
            ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
            for (JsonNode node : dataset) {
                if (node.has("source")) {
                    ((ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                    break;
                }
            }

            // 移除集合中第一个对象的第一个元素
            if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                lists.get(0).remove(0);
            }
            ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
            // 计算第一个对象元素数量
            int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();
            System.out.println(firstObjectRemainingElements);

            // 如果series字段的对象数量小于第一个集合的数量，循环复制series中的对象使其数量相等
            if (seriesArray.size() < firstObjectRemainingElements) {
                JsonNode firstSeriesObject = seriesArray.get(0);
                for (int i = seriesArray.size(); i < firstObjectRemainingElements; i++) {
                    seriesArray.add(firstSeriesObject.deepCopy());
                }
            } else {
                // 删除多余的对象
                while (seriesArray.size() > firstObjectRemainingElements) {
                    seriesArray.remove(seriesArray.size() - 1);
                }
            }
            // 更新series中每个对象的name字段
            for (int i = 0; i < firstObjectRemainingElements; i++) {
                ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
            }

            // 获取legend节点并更新data
            JsonNode legend = chartValueJson.path("legend");
            ChartDataUtils.updateLegendData(legend, lists);


            // 处理颜色字段
            ObjectNode jsonNode = (ObjectNode) objectMapper.readTree(chartValue);
            // 获取 color 字段
            JsonNode colorNode = jsonNode.path("color");
            List<String> baseColors = new ArrayList<>();
            // 遍历 color 数组并将每个颜色值添加到 baseColors 集合中
            if (colorNode.isArray()) {
                for (JsonNode color : colorNode) {
                    String colorValue = color.asText();
                    baseColors.add(colorValue);
                }
            }

            int beforeSize = baseColors.size();
            int afterSize = lists.get(0).size();
            if (beforeSize < afterSize) {
                chartValueJson = ColorUtils.processChartColorsHert(JSON.toJSONString(chartValueJson), afterSize);
            }
            String updatedChartValue = chartValueJson.toString();
            ArrayList<ChartSmartVo> newList = new ArrayList<>();
            // 获取ChartConfigs对象
            ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
            // 创建新的ChartSmartVo对象并设置属性
            ChartSmartVo chartSmartVo = new ChartSmartVo();
            chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
            chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
            chartSmartVo.setConfigValue(updatedChartValue);
            chartSmartVo.setChartTypeId(configs.getChartTypeId());
            newList.add(chartSmartVo);
            System.out.println(updatedChartValue);
            return AjaxResult.success(newList);

        }
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }


    //带包络线的分组堆叠柱状图
    @PostMapping("/stackedColumnSmoothed/importData")
    public AjaxResult stackedColumnSmoothed(@RequestBody ChartDateTto chartDateTto) throws Exception {
        Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());
        List<List<String>> getData = ExcelDataUtils.getData(sheet);
        if (CollectionUtils.isEmpty(getData)) {
            return AjaxResult.error("请填充数据");
        }
        List<String> firstName = new ArrayList<>();
        List<String> nameList = getData.get(0);

        for (String s : nameList) {
            if (ObjectUtils.isNotEmpty(s) && !s.isEmpty()) {
                firstName.add(s);
            }
        }
        List<String> roomName = new ArrayList<>();
        List<List<String>> list = new ArrayList<>();
        list.add(firstName);

        List<Map<String, Object>> datasets = new ArrayList<>();

        for (int i = 1; i < getData.size(); i++) {
            List<String> rowData = getData.get(i);
            if (!CollectionUtils.isEmpty(rowData)) {
                List<String> data = new ArrayList<>();
                for (String s : rowData) {
                    if (ObjectUtils.isNotEmpty(s) && !s.isEmpty()) {
                        data.add(s);
                    }
                }

                if (data.size() == 1) {
                    if (i != 1) {
                        Map<String, Object> dataset = new HashMap<>();
                        dataset.put("source", list);
                        datasets.add(dataset);
                        list = new ArrayList<>();
                        list.add(firstName);
                    }
                    roomName.add(data.get(0));
                } else {
                    list.add(data);
                    if (i == getData.size() - 1) {
                        Map<String, Object> dataset = new HashMap<>();
                        dataset.put("source", list);
                        datasets.add(dataset);
                    }
                }
            }
        }

        JSONObject jsonObject = JSON.parseObject(chartDateTto.getChartValue());
        List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
        JSONObject seriesTemplate = series.get(0);
        List<JSONObject> sDatas = new ArrayList<>();

        if (roomName.isEmpty()) {
            for (int i = 1; i < firstName.size(); i++) {
                JSONObject object = new JSONObject();
                object.putAll(seriesTemplate);
                object.put("name", firstName.get(i));
                sDatas.add(object);
            }
        } else {
            for (int i = 0; i < roomName.size(); i++) {
                for (int j = 1; j < firstName.size(); j++) {
                    JSONObject object = new JSONObject();
                    object.putAll(seriesTemplate);
                    object.put("stack", roomName.get(i));
                    object.put("datasetIndex", i);
                    object.put("name", firstName.get(j));
                    sDatas.add(object);
                }
            }
        }

        jsonObject.put("dataset", datasets);
        jsonObject.put("series", sDatas);

        // Handle the legend as a JSONArray
        Object legendObject = jsonObject.get("legend");
        if (legendObject instanceof JSONArray) {
            JSONArray legendArray = (JSONArray) legendObject;
            // Assuming you want to modify the first object in the array
            if (!legendArray.isEmpty()) {
                JSONObject legend = legendArray.getJSONObject(0);
                List<ChartLegendData> chartLegendData = new ArrayList<>();
                for (int i = 1; i < firstName.size(); i++) {
                    ChartLegendData data = new ChartLegendData();
                    data.setName(firstName.get(i));
                    chartLegendData.add(data);
                }
                legend.put("data", chartLegendData);
            }
        } else if (legendObject instanceof JSONObject) {
            JSONObject legend = (JSONObject) legendObject;
            List<ChartLegendData> chartLegendData = new ArrayList<>();
            for (int i = 1; i < firstName.size(); i++) {
                ChartLegendData data = new ChartLegendData();
                data.setName(firstName.get(i));
                chartLegendData.add(data);
            }
            legend.put("data", chartLegendData);
            jsonObject.put("legend", legend);
        }
        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId());
        chartSmartVo.setConfigName(configs.getConfigName());
        chartSmartVo.setConfigValue(JSON.toJSONString(jsonObject));
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(JSON.toJSONString(jsonObject));
        return AjaxResult.success(newList);

    }
/*    //带包络线的分组堆叠柱状图
    @PostMapping("/stackedColumnSmoothed/importData")
    public AjaxResult stackedColumnSmoothed(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> fistName = new ArrayList<>();
            List<String> nameList = getdata.get(0);
            for (int i = 0; i < nameList.size(); i++) {
                String s = nameList.get(i);
                if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                    fistName.add(s);
                }
            }

            List<String> roomName = getdata.get(1);

            List<Integer> roomNameIndex = new ArrayList<>();
            int k = 0;

            List<ChartXData> xDatas = new ArrayList<>();


            List<List<String>> list = new ArrayList<>();
            for (int i = 2; i < getdata.size(); i++) {
                if (getdata.get(i).size() == 1) {
                    list.add(0, fistName);
                    ChartXData chartXData = new ChartXData();
                    chartXData.setSource(list);
                    xDatas.add(chartXData);
                    list = new ArrayList<>();
                    roomNameIndex.add(k);
                    roomName.add(getdata.get(i).get(0));
                    k = 0;
                } else {
                    k++;
                    List<String> strings=new ArrayList<>();
                    List<String> oldList = getdata.get(i);
                    for (int i1 = 0; i1 < oldList.size(); i1++) {
                        String s = oldList.get(i1);
                        if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                            strings.add(s);
                        }
                    }
                    list.add(strings);
                }
                if (i == getdata.size() - 1) {
                    k++;
                    list.add(0, fistName);
                    ChartXData chartXData = new ChartXData();
                    chartXData.setSource(list);
                    xDatas.add(chartXData);
                    roomNameIndex.add(k);
                }
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject series1 = series.get(0);
            List<JSONObject> sDatas = new ArrayList<>();


            fistName.remove(0);
            if (roomName.size() < 1) {
                for (int i = 0; i < fistName.size(); i++) {
                    JSONObject object = new JSONObject();
                    object.putAll(series1);
                    object.put("stack", roomName.get(i));
                    object.put("name", fistName.get(i));
                    sDatas.add(object);
                }
            } else {
                for (int i = 0; i < roomNameIndex.size(); i++) {
//                Integer indexNum = roomNameIndex.get(i);
                    for (Integer integer = 0; integer < fistName.size(); integer++) {
                        JSONObject object = new JSONObject();
                        object.putAll(series1);
                        object.put("stack", roomName.get(i));
                        object.put("datasetIndex", i);
                        object.put("name", fistName.get(integer));
                        sDatas.add(object);
                    }
                }
            }


            ChartData chartData = new ChartData();
            chartData.setDataset(xDatas);

            jsonObject.put("dataset", xDatas);
            jsonObject.put("series", sDatas);

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            List<ChartLegendData> chartLegendData = new ArrayList<>();
            for (int i = 0; i < fistName.size(); i++) {
                ChartLegendData data = new ChartLegendData();
                data.setName(fistName.get(i));
                chartLegendData.add(data);
            }
            legend.put("data", chartLegendData);
            jsonObject.put("legend", legend);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/


    //带包络线的分组堆叠柱状图
    @PostMapping("/stackedColumnSmoothed/v2/importData")
    public AjaxResult v2stackedColumnSmoothed(@RequestBody List<Map<String, Object>> dataLists
            , Long configId) throws Exception {
        //  XSSFWorkbook workbook = null;
        try {
          /*  workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> fistName = new ArrayList<>();
            List<String> nameList = getdata.get(0);
            for (int i = 0; i < nameList.size(); i++) {
                String s = nameList.get(i);
                if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                    fistName.add(s);
                }
            }

            List<String> roomName = getdata.get(1);

            List<Integer> roomNameIndex = new ArrayList<>();
            int k = 0;

            List<ChartXData> xDatas = new ArrayList<>();


            List<List<String>> list = new ArrayList<>();
            for (int i = 2; i < getdata.size(); i++) {
                if (getdata.get(i).size() == 1) {
                    list.add(0, fistName);
                    ChartXData chartXData = new ChartXData();
                    chartXData.setSource(list);
                    xDatas.add(chartXData);
                    list = new ArrayList<>();
                    roomNameIndex.add(k);
                    roomName.add(getdata.get(i).get(0));
                    k = 0;
                } else {
                    k++;
                    List<String> strings = new ArrayList<>();
                    List<String> oldList = getdata.get(i);
                    for (int i1 = 0; i1 < oldList.size(); i1++) {
                        String s = oldList.get(i1);
                        if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                            strings.add(s);
                        }
                    }
                    list.add(strings);
                }
                if (i == getdata.size() - 1) {
                    k++;
                    list.add(0, fistName);
                    ChartXData chartXData = new ChartXData();
                    chartXData.setSource(list);
                    xDatas.add(chartXData);
                    roomNameIndex.add(k);
                }
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject series1 = series.get(0);
            List<JSONObject> sDatas = new ArrayList<>();


            fistName.remove(0);
            if (roomName.size() < 1) {
                for (int i = 0; i < fistName.size(); i++) {
                    JSONObject object = new JSONObject();
                    object.putAll(series1);
                    object.put("stack", roomName.get(i));
                    object.put("name", fistName.get(i));
                    sDatas.add(object);
                }
            } else {
                for (int i = 0; i < roomNameIndex.size(); i++) {
//                Integer indexNum = roomNameIndex.get(i);
                    for (Integer integer = 0; integer < fistName.size(); integer++) {
                        JSONObject object = new JSONObject();
                        object.putAll(series1);
                        object.put("stack", roomName.get(i));
                        object.put("datasetIndex", i);
                        object.put("name", fistName.get(integer));
                        sDatas.add(object);
                    }
                }
            }


            ChartData chartData = new ChartData();
            chartData.setDataset(xDatas);

            jsonObject.put("dataset", xDatas);
            jsonObject.put("series", sDatas);

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            List<ChartLegendData> chartLegendData = new ArrayList<>();
            for (int i = 0; i < fistName.size(); i++) {
                ChartLegendData data = new ChartLegendData();
                data.setName(fistName.get(i));
                chartLegendData.add(data);
            }
            legend.put("data", chartLegendData);
            jsonObject.put("legend", legend);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            //workbook.close();
        }
    }

    //水平条形柱状图
    @PostMapping("/horizontalBar/importData")
    public AjaxResult horizontalBar(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }
/*    //水平条形柱状图
    @PostMapping("/horizontalBar/importData")
    public AjaxResult horizontalBar(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getColData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<Map> roomName = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                HashMap<String, String> map = new HashMap<>();
                String name = strings.get(0);
                if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(name) || !name.equals("")) {
                    map.put("name", strings.get(0));
                }
                roomName.add(map);
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data",roomName);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject json = series.get(0);
            ArrayList<JSONObject> list = new ArrayList<>();

            for (int i = 0; i < roomName.size(); i++) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.putAll(json);
                jsonObject1.put("name",roomName.get(i).get("name"));
                List<String> list1 = getdata.get(i+1);
                ArrayList<String> newList = new ArrayList<>();
                for (int i1 = 0; i1 < list1.size(); i1++) {
                    String s = list1.get(i1);
                    if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        newList.add(s);
                    }
                }
                if (newList.size() >= 2) {
                    List<String> sublistExcludingFirstTwo = newList.subList(1, list1.size());
                    jsonObject1.put("data",sublistExcludingFirstTwo);
                }
                list.add(jsonObject1);
            }

            jsonObject.put("legend",legend);
            jsonObject.put("series",list);

            ArrayList<String> strings = new ArrayList<>();
            List<String> list1 = getdata.get(0);
            for (int i = 1; i < list1.size(); i++) {
                String s = list1.get(i);
                if (ObjectUtils.isNotEmpty(s) && !s.equals(s)) {
                    strings.add(s);
                }
            }
            JSONObject yAxis = (JSONObject) jsonObject.get("yAxis");
            yAxis.put("data",strings);
            jsonObject.put("yAxis",yAxis);


            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/

    //前8行是空白
    public static Sheet convertDataListToSheets(List<Map<String, Object>> dataList) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        // Insert 8 blank rows before starting the data
        for (int i = 0; i < 8; i++) {
            sheet.createRow(i);
        }

        // Populate sheet with data starting from the ninth row
        int rowIndex = 8; // Start from the ninth row
        for (Map<String, Object> data : dataList) {
            Row row = sheet.createRow(rowIndex++);
            int cellIndex = 0;
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                Cell cell = row.createCell(cellIndex++);
                setCellValue(cell, entry.getValue());
            }
        }

        return sheet;
    }


    //水平条形柱状图
    @PostMapping("/horizontalBar/v2/importData")
    public AjaxResult vhorizontalBar(@RequestBody List<Map<String, Object>> dataList, Long configId) throws Exception {
        //  XSSFWorkbook workbook = null;
        try {
         /*   workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = convertDataListToSheets(dataList);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getColData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<Map> roomName = new ArrayList<>();

            for (int i = 1; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                HashMap<String, String> map = new HashMap<>();
                String name = strings.get(0);
                if (ObjectUtils.isNotEmpty(name) || !name.equals("")) {
                    map.put("name", strings.get(0));
                }
                roomName.add(map);
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data", roomName);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject json = series.get(0);
            ArrayList<JSONObject> list = new ArrayList<>();

            for (int i = 0; i < roomName.size(); i++) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.putAll(json);
                jsonObject1.put("name", roomName.get(i).get("name"));
                List<String> list1 = getdata.get(i + 1);
                ArrayList<String> newList = new ArrayList<>();
                for (int i1 = 0; i1 < list1.size(); i1++) {
                    String s = list1.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        newList.add(s);
                    }
                }
                if (newList.size() >= 2) {
                    List<String> sublistExcludingFirstTwo = newList.subList(1, list1.size());
                    jsonObject1.put("data", sublistExcludingFirstTwo);
                }
                list.add(jsonObject1);
            }

            jsonObject.put("legend", legend);
            jsonObject.put("series", list);

            ArrayList<String> strings = new ArrayList<>();
            List<String> list1 = getdata.get(0);
            for (int i = 1; i < list1.size(); i++) {
                String s = list1.get(i);
                if (ObjectUtils.isNotEmpty(s) && !s.equals(s)) {
                    strings.add(s);
                }
            }
            JSONObject yAxis = (JSONObject) jsonObject.get("yAxis");
            yAxis.put("data", strings);
            jsonObject.put("yAxis", yAxis);


            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            // workbook.close();
        }
    }

    //基础柱状图
    @PostMapping("/basic/importData")
    public AjaxResult basic(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }
/*    //基础柱状图
    @PostMapping("/basic/importData")
    public AjaxResult basic(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getColData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<Map> roomName = new ArrayList<>();


            List<String> strings = getdata.get(1);
            HashMap<String, String> map = new HashMap<>();
            map.put("name", strings.get(0));
            roomName.add(map);

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data",roomName);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");

            ArrayList<JSONObject> list = new ArrayList<>();
            for (int i = 0; i < series.size(); i++) {
                JSONObject o1 = series.get(i);
                o1.put("name",roomName.get(i).get("name"));
                List<String> list1 =getdata.get(i+1);
                ArrayList<String> newList = new ArrayList<>();
                for (int i1 = 1; i1 < list1.size(); i1++) {
                    String s = list1.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        newList.add(s);
                    }
                }
                o1.put("data",newList);
                list.add(o1);
            }

            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
            List<String> strings1 = getdata.get(0);
            strings1.remove(0);

            xAxis.put("data",strings1);

            jsonObject.put("xAxis",xAxis);
            jsonObject.put("legend",legend);
            jsonObject.put("series",list);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }*/


    //带背景色的柱状图
    @PostMapping("/background/v2/importData")
    public AjaxResult v2background(@RequestBody List<Map<String, Object>> dataList
            , Long configId) throws Exception {
        //XSSFWorkbook workbook = null;
        try {
           /* workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataList);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getColData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<Map> roomName = new ArrayList<>();


            List<String> strings = getdata.get(1);
            HashMap<String, String> map = new HashMap<>();
            map.put("name", strings.get(0));
            roomName.add(map);

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject legend = (JSONObject) jsonObject.get("legend");
            legend.put("data", roomName);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");

            ArrayList<JSONObject> list = new ArrayList<>();
            for (int i = 0; i < series.size(); i++) {
                JSONObject o1 = series.get(i);
                o1.put("name", roomName.get(i).get("name"));
                List<String> list1 = getdata.get(i + 1);
                ArrayList<String> newList = new ArrayList<>();
                for (int i1 = 1; i1 < list1.size(); i1++) {
                    String s = list1.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        newList.add(s);
                    }
                }
                o1.put("data", newList);
                list.add(o1);
            }
            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
            List<String> strings1 = getdata.get(0);
            strings1.remove(0);

            xAxis.put("data", strings1);

            jsonObject.put("xAxis", xAxis);
            jsonObject.put("legend", legend);
            jsonObject.put("series", list);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            //workbook.close();
        }
    }

    //带背景色的柱状图
    @PostMapping("/background/importData")
    public AjaxResult background(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }

    /*    //带背景色的柱状图
        @PostMapping("/background/importData")
        public AjaxResult background(MultipartFile file,Long configId) throws Exception {
            XSSFWorkbook workbook = null;
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
                Sheet sheet = workbook.getSheetAt(1);
                //获取
                List<List<String>> getdata = ExcelDataUtils.getColData(sheet);

                if (CollectionUtils.isEmpty(getdata)) {
                    return AjaxResult.error("请填充数据");
                }

                List<Map> roomName = new ArrayList<>();


                List<String> strings = getdata.get(1);
                HashMap<String, String> map = new HashMap<>();
                map.put("name", strings.get(0));
                roomName.add(map);

                ChartConfigs configs = chartConfigsService.getById(configId);
                JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

                JSONObject legend = (JSONObject) jsonObject.get("legend");
                legend.put("data",roomName);

                List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");

                ArrayList<JSONObject> list = new ArrayList<>();
                for (int i = 0; i < series.size(); i++) {
                    JSONObject o1 = series.get(i);
                    o1.put("name",roomName.get(i).get("name"));
                    List<String> list1 =getdata.get(i+1);
                    ArrayList<String> newList = new ArrayList<>();
                    for (int i1 = 1; i1 < list1.size(); i1++) {
                        String s = list1.get(i1);
                        if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                            newList.add(s);
                        }
                    }
                    o1.put("data",newList);
                    list.add(o1);
                }
                JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
                List<String> strings1 = getdata.get(0);
                strings1.remove(0);

                xAxis.put("data",strings1);

                jsonObject.put("xAxis",xAxis);
                jsonObject.put("legend",legend);
                jsonObject.put("series",list);

                return AjaxResult.success(JSON.toJSONString(jsonObject));
            }finally {
                workbook.close();
            }
        }*/
//归一化堆叠柱状图
    @PostMapping("/singleStackedColumn/importData")
    public AjaxResult multiLineSmoothLine(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }
  /*  //归一化堆叠柱状图
    @PostMapping("/singleStackedColumn/importData")
    public AjaxResult multiLineSmoothLine(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> xlist = new ArrayList<>();
            List<String> firstName = new ArrayList<>();
            List<List<Double>> dataList = new ArrayList<>();
            for (int i = 0; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                ArrayList<String> newList = new ArrayList<>();
                double snum=0;
                for (int i1 = 0; i1 < rowData.size(); i1++) {
                    String s = rowData.get(i1);
                    if (!org.springframework.util.ObjectUtils.isEmpty(s) && !s.equals("")) {
                        newList.add(s);
                        if (i != 0) {
                            if (i1 !=0) {
                                snum += Double.parseDouble(s);
                            }
                        }
                    }
                }

                List<Double> doubles = new ArrayList<>();
                if (!CollectionUtils.isEmpty(newList)) {
                    if (i == 0) {
                        firstName.addAll(newList);
                    } else {
                        for (int i1 = 0; i1 < newList.size(); i1++) {
                            String s = newList.get(i1);
                            if (i1==0) {
                                xlist.add(s);
                            }else {
                                double v = Double.parseDouble(s);
                                doubles.add(v/snum);
                            }
                        }
                    }
                    if (!CollectionUtils.isEmpty(doubles)) {
                        dataList.add(doubles);
                    }

                }
            }

            firstName.remove(0);
            List<List<Double>> datass = new ArrayList<>();
            for (int i = 0; i < firstName.size(); i++) {
                List<Double> datas = new ArrayList<>();
                datass.add(datas);
            }


            for (int i = 0; i < dataList.size(); i++) {
                List<Double> doubles = dataList.get(i);
                for (int i1 = 0; i1 < doubles.size(); i1++) {
                    List<Double> doubles1 = datass.get(i1);
                    doubles1.add(doubles.get(i1));
                }
            }



            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
//        xlist.remove(0);
            xAxis.put("data",xlist);
            jsonObject.put("xAxis",xAxis);

            JSONObject legend = (JSONObject) jsonObject.get("legend");

            List<JSONObject> newList =new ArrayList<>();
            List<Map> maps =new ArrayList<>();
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            for (int i = 0; i < firstName.size(); i++) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.putAll(jsonObject1);

                jsonObject2.put("name",firstName.get(i));
                Map<String, String> map = new HashMap<>();
                map.put("name",firstName.get(i));
                maps.add(map);
                jsonObject2.put("data",datass.get(i));
                newList.add(jsonObject2);
            }
            legend.put("data",maps);
            jsonObject.put("legend",legend);

            jsonObject.put("series",newList);


            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally{
            workbook.close();
        }
    }*/

    //归一化堆叠柱状图
    @PostMapping("/singleStackedColumn/v2/importData")
    public AjaxResult v2multiLineSmoothLine(@RequestBody List<Map<String, Object>> dataLists
            , Long configId) throws Exception {
        //  XSSFWorkbook workbook = null;
        try {
         /*   workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> xlist = new ArrayList<>();
            List<String> firstName = new ArrayList<>();
            List<List<Double>> dataList = new ArrayList<>();
            for (int i = 0; i < getdata.size(); i++) {
                List<String> rowData = getdata.get(i);
                ArrayList<String> newList = new ArrayList<>();
                double snum = 0;
                for (int i1 = 0; i1 < rowData.size(); i1++) {
                    String s = rowData.get(i1);
                    if (!org.springframework.util.ObjectUtils.isEmpty(s) && !s.equals("")) {
                        newList.add(s);
                        if (i != 0) {
                            if (i1 != 0) {
                                snum += Double.parseDouble(s);
                            }
                        }
                    }
                }

                List<Double> doubles = new ArrayList<>();
                if (!CollectionUtils.isEmpty(newList)) {
                    if (i == 0) {
                        firstName.addAll(newList);
                    } else {
                        for (int i1 = 0; i1 < newList.size(); i1++) {
                            String s = newList.get(i1);
                            if (i1 == 0) {
                                xlist.add(s);
                            } else {
                                double v = Double.parseDouble(s);
                                doubles.add(v / snum);
                            }
                        }
                    }
                    if (!CollectionUtils.isEmpty(doubles)) {
                        dataList.add(doubles);
                    }

                }
            }

            firstName.remove(0);
            List<List<Double>> datass = new ArrayList<>();
            for (int i = 0; i < firstName.size(); i++) {
                List<Double> datas = new ArrayList<>();
                datass.add(datas);
            }


            for (int i = 0; i < dataList.size(); i++) {
                List<Double> doubles = dataList.get(i);
                for (int i1 = 0; i1 < doubles.size(); i1++) {
                    List<Double> doubles1 = datass.get(i1);
                    doubles1.add(doubles.get(i1));
                }
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            JSONObject xAxis = (JSONObject) jsonObject.get("xAxis");
//        xlist.remove(0);
            xAxis.put("data", xlist);
            jsonObject.put("xAxis", xAxis);

            JSONObject legend = (JSONObject) jsonObject.get("legend");

            List<JSONObject> newList = new ArrayList<>();
            List<Map> maps = new ArrayList<>();
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            for (int i = 0; i < firstName.size(); i++) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.putAll(jsonObject1);

                jsonObject2.put("name", firstName.get(i));
                Map<String, String> map = new HashMap<>();
                map.put("name", firstName.get(i));
                maps.add(map);
                jsonObject2.put("data", datass.get(i));
                newList.add(jsonObject2);
            }
            legend.put("data", maps);
            jsonObject.put("legend", legend);

            jsonObject.put("series", newList);


            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            // workbook.close();
        }
    }
}
